﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Prism.Commands;
using Prism.Mvvm;
using WpfCallScreen.Common;
using Prism.Unity;
using System.Speech.Synthesis;
using WpfCallScreen.Models;
using System.ComponentModel;
using System.Windows.Threading;
using Newtonsoft.Json;
using System.Diagnostics;
using System.IO;

namespace WpfCallScreen.ViewModels
{
    public class MainViewModel : BindableBase
    {
        private string _InPutMsg;

        public string InPutMsg
        {
            get { return _InPutMsg; }
            set
            {
                _InPutMsg = value;
                RaisePropertyChanged(nameof(InPutMsg));
            }
        }
        private string _CallMsg;

        public string CallMsg
        {
            get { return _CallMsg; }
            set
            {
                _CallMsg = value;
                RaisePropertyChanged(nameof(CallMsg));
            }
        }

        private List<Patient> _PatList;
        public List<Patient> PatList
        {
            get
            {
                return _PatList;
            }
            set
            {
                _PatList = value;
                RaisePropertyChanged(nameof(PatList));
            }
        }
        private List<Patient> AllPatList = new List<Patient>();

        public DelegateCommand<object> CallNextCommand { get; set; }
        public DelegateCommand<object> LoadDataCommand { get; set; }
        public DelegateCommand<object> CloseCommand { get; set; }
        private static string url = "ws://127.0.0.1:5000/ws";
        private WSocketClient client;
        public MainViewModel()
        {
            url= WinConfigHelper.GetValue("SocketServer");
            client = new WSocketClient(url);
            InPutMsg = "测试呼叫";
            CallNextCommand = new DelegateCommand<object>(OnCallNext);
            CloseCommand = new DelegateCommand<object>(OnClose);
            //LoadDataCommand = new DelegateCommand<object>(OnLoadData);
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 3); //每隔1秒触发一次事件
            timer.Tick += new EventHandler(timer_Tick); //注册事件处理函数
            timer.Start(); //启动定时器
            client.MessageReceived = MessageReceived;
            LoadExe();
        }
        /// <summary>
        /// 退出程序
        /// </summary>
        /// <param name="obj"></param>
        private void OnClose(object obj)
        {
            client.Dispose();
            Environment.Exit(0);
        }

        /// <summary>
        /// 准备完毕
        /// </summary>
        public void Loaded()
        {
            client.Start();

            //进入组
            Message mg = new Message();
            mg.Action = "join";
            mg.Msg = "CallScreen";
            mg.Name = "Screen";
            mg.SendClientId = "";
            var message = JsonConvert.SerializeObject(mg);
            client.SendMessage(message);

            Task.Factory.StartNew(() =>
            {
                while (CallHelper.isOpen)
                {
                    //lock (CallHelper.playLockObj)
                    //{
                    string item;
                    if (CallHelper.MsgQueue.TryDequeue(out item))
                    {

                        CallMsg = "当前呼叫内容：【" + item + "]";
                        CallHelper.sp.Play();
                        using (SpeechSynthesizer speech = new SpeechSynthesizer())
                        {
                            speech.Rate = 0;
                            speech.Volume = 100;
                            speech.Speak(item);
                        }

                    }
                    Task.Delay(100);
                    //}
                }
            });

        }
        /// <summary>
        /// 模拟数据库加载数据
        /// </summary>
        /// <param name="obj"></param>
        private void OnLoadData(object obj)
        {
            Task.Delay(500).Wait();
            List<Patient> tempALlList = new List<Patient>();
            Random random = new Random();
            int number = random.Next(90, 120);
            for (int i = 0; i < number; i++)
            {
                Patient a = new Patient();
                a.Num = i;
                a.Name = "测试" + i;
                a.Sex = (i % 2) == 0 ? "男" : "女";
                a.DeptName = "急诊科";
                a.VisitDate = DateTime.Now;
                tempALlList.Add(a);
            }
            AllPatList = tempALlList;

        }

        int PageSize = 10;
        int PageCount = 0;
        int CurrPage = 1;

        /// <summary>
        /// 定时器任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void timer_Tick(object sender, EventArgs e)
        {
            if (CurrPage > PageCount || PageCount == 0)
            {
                OnLoadData(null);
                //拉取数据源
                int allCount = AllPatList.Count;
                PageCount =(int) Math.Ceiling((double)allCount / (double)PageSize);
                CurrPage = 1;
            }
            if (PageCount <= 0)
            {
                return;
            }
            int start = (CurrPage - 1) * PageSize;//
            int end = CurrPage * PageSize;
            //滚动屏幕

            if (CurrPage != PageCount)
            {
                PatList = AllPatList.FindAll(c => c.Num >= start && c.Num < end);
            }
            else
            {
                PatList = AllPatList.FindAll(c => c.Num >= start);
            }
            CurrPage++;
        }

        /// <summary>
        /// 呼叫
        /// </summary>
        /// <param name="obj"></param>
        private void OnCallNext(object obj)
        {
            CallHelper.PutMsg(obj.ToString());
        }

        /// <summary>
        /// 服务端返回的消息
        /// </summary>
        private void MessageReceived(string msg)
        {
            CallHelper.PutMsg(msg);
        }
        /// <summary>
        /// 启动外部程序-网页
        /// </summary>
        private void LoadExe() 
        {
            // 创建一个新的ProcessStartInfo实例
            ProcessStartInfo startInfo = new ProcessStartInfo();
            string baseurl = AppDomain.CurrentDomain.BaseDirectory;
            // 设置exe文件的路径（这里以notepad.exe为例）
            startInfo.FileName = Path.Combine(baseurl, "screen.url");
            startInfo.CreateNoWindow = true;
            // 如果需要，可以添加启动参数（例如打开特定的文件）
            // startInfo.Arguments = @"C:\path\to\your\file.txt";
            try
            {
                // 启动外部程序
                Process exeProcess = Process.Start(startInfo);
                // 可选：等待外部程序退出
                //exeProcess.WaitForExit();

                // 如果需要，可以获取退出代码
                //int exitCode = exeProcess.ExitCode;
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                // 处理错误情况，例如文件不存在
                Console.WriteLine(ex.Message);
            }
        }
    }
    
}
